package com.yfy.web.controller.admin;


import com.github.pagehelper.PageInfo;
import com.yfy.model.ResponseData.ArticleResponseData;
import com.yfy.model.ResponseData.StatisticsBo;
import com.yfy.model.entity.Article;
import com.yfy.model.entity.Comment;
import com.yfy.model.entity.User;
import com.yfy.service.ArticleService;
import com.yfy.service.CommentService;
import com.yfy.service.SiteService;
import com.yfy.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * @Author yfy2001
 * @date 2022/11/15 13:00
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private SiteService siteServiceImpl;
    @Autowired
    private ArticleService articleServiceImpl;
    @Autowired
    private CommentService commentServiceImpl;
    @Autowired
    private UserService userServiceImpl;

    // 管理中心起始页
    @GetMapping(value = {"", "/index"})
    public String index(HttpServletRequest request) {
        // 获取最新的5篇博客、评论以及统计数据
        List<Article> articles = siteServiceImpl.recentArticles(5);
        List<Comment> comments = siteServiceImpl.recentComments(5);
        StatisticsBo statisticsBo = siteServiceImpl.getStatistics();
        // 向Request域中存储数据
        request.setAttribute("comments", comments);
        request.setAttribute("articles", articles);
        request.setAttribute("statistics", statisticsBo);
        return "back/index";
    }

    // 向文章发表页面跳转
    @GetMapping(value = "/article/toEditPage")
    public String newArticle( ) {
        return "back/article_edit";
    }
    // 发表文章
    @PostMapping(value = "/article/publish")
    @ResponseBody
    public ArticleResponseData publishArticle(Article article) {
        if (StringUtils.isBlank(article.getCategories())) {
            article.setCategories("默认分类");
        }
        try {
            articleServiceImpl.publish(article);
            logger.info("文章发布成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("文章发布失败，错误信息: "+e.getMessage());
            return ArticleResponseData.fail();
        }
    }
    // 跳转到后台文章列表页面
    @GetMapping(value = "/article")
    public String index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "count", defaultValue = "10") int count,
                        HttpServletRequest request) {
        PageInfo<Article> pageInfo = articleServiceImpl.selectArticleWithPage(page, count);
        request.setAttribute("articles", pageInfo);
        return "back/article_list";
    }

    /**
     * 跳转到后台评论列表页面
     * @param page
     * @param count
     * @param request
     * @return
     */
    @GetMapping(value = "/comment")
    public String comment(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "count", defaultValue = "10") int count,
                        HttpServletRequest request) {
        PageInfo<Comment> pageInfo = commentServiceImpl.selectCommentWithPage(page, count);
        request.setAttribute("comments", pageInfo);
        return "back/comment_list";
    }

    /**
     * 跳转到后台用户列表页面
     * @param page
     * @param count
     * @param request
     * @return
     */
    @GetMapping(value = "/user")
    public String user(@RequestParam(value = "page", defaultValue = "1") int page,
                          @RequestParam(value = "count", defaultValue = "10") int count,
                          HttpServletRequest request) {
        PageInfo<User> pageInfo = userServiceImpl.selectUserWithPage(page, count);
        request.setAttribute("users", pageInfo);
        return "back/user_list";
    }

    // 向文章修改页面跳转
    @GetMapping(value = "/article/{id}")
    public String editArticle(@PathVariable("id") String id, HttpServletRequest request) {
        Article article = articleServiceImpl.selectArticleWithId(Long.parseLong(id));
        request.setAttribute("contents", article);
        request.setAttribute("categories", article.getCategories());
        return "back/article_edit";
    }

    // 文章修改处理
    @PostMapping(value = "/article/modify")
    @ResponseBody
    public ArticleResponseData modifyArticle(Article article) {
        try {
            articleServiceImpl.updateArticleWithId(article);
            logger.info("文章更新成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("文章更新失败，错误信息: "+e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 文章删除
    @PostMapping(value = "/article/delete")
    @ResponseBody
    public ArticleResponseData delete(@RequestParam Long id) {
        try {
            articleServiceImpl.deleteArticleWithId(id);
            logger.info("文章删除成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("文章删除失败，错误信息: "+e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    /**
     * 评论删除
     * @param id
     * @return
     */
    @PostMapping(value = "/comment/delete")
    @ResponseBody
    public ArticleResponseData deleteComment(@RequestParam Long id) {
        try {
            commentServiceImpl.deleteComment(id);
            logger.info("评论删除成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("评论删除失败，错误信息: "+e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    /**
     * 用户删除（逻辑删除）
     * @param id
     * @return
     */
    @PostMapping(value = "/user/delete")
    @ResponseBody
    public ArticleResponseData deleteUser(@RequestParam Long id) {
        User user=new User();
        user.setId(id);
        try {
            userServiceImpl.logicDeletedUser(user);
            logger.info("用户删除成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("用户删除失败，错误信息: "+e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    /**
     * 取消删除用户
     * @param id
     * @return
     */
    @PostMapping(value = "/user/undelete")
    @ResponseBody
    public ArticleResponseData undeleteUser(@RequestParam Long id) {
        User user=new User();
        user.setId(id);
        try {
            userServiceImpl.unDeletedUser(user);
            logger.info("取消用户删除成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("取消用户删除失败，错误信息: "+e.getMessage());
            return ArticleResponseData.fail();
        }
    }
}
